


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>Testing Actor Systems (Scala) &mdash; Akka Documentation</title>
    
    <link rel="stylesheet" href="../_static/style.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <link rel="stylesheet" href="../_static/prettify.css" type="text/css" />
    <link rel="stylesheet" href="../_static/base.css" type="text/css" />
    <link rel="stylesheet" href="../_static/docs.css" type="text/css" />
    <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Exo:300,400,600,700" type="text/css" />
    
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../',
        VERSION:     '2.0.1',
        COLLAPSE_INDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/toc.js"></script>
    <script type="text/javascript" src="../_static/prettify.js"></script>
    <script type="text/javascript" src="../_static/highlightCode.js"></script>
    <script type="text/javascript" src="../_static/effects.core.js"></script>
    <script type="text/javascript" src="../_static/effects.highlight.js"></script>
    <script type="text/javascript" src="../_static/scrollTo.js"></script>
    <script type="text/javascript" src="../_static/contentsFix.js"></script>
    <link rel="shortcut icon" href="../_static/favicon.ico"/>
    <link rel="top" title="Akka Documentation" href="../index.html" />
    <link rel="up" title="Scala API" href="index.html" />
    <link rel="next" title="TestKit Example (Scala)" href="testkit-example.html" />
    <link rel="prev" title="IO (Scala)" href="io.html" /> 
  </head>
  <body>
  <div class="navbar">
    <div class="navbar-inner">
      <div class="container">
        <div class="navbar-logo">
          <a href="http://akka.io"><img src="../_static/logo-small.png" /></a>
        </div>    
        <ul class="nav">
          <li><a href="http://akka.io/docs">Documentation</a></li>
          <li><a href="http://akka.io/downloads">Download</a></li>
          <li><a href="http://groups.google.com/group/akka-user">Mailing List</a></li>
          <li><a href="http://github.com/akka/akka">Code</a></li>           
          <li><a href="http://typesafe.com/products/typesafe-subscription">Commerical Support</a></li>
        </ul>
      </div>
    </div>
  </div>
  <div class="main">
    <div class="container">
      <div class="page-title">Testing Actor Systems (Scala)</div><div class="pdf-link"><a href="http://akka.io/docs/akka/2.0.1/Akka.pdf"><img src="../_static/pdf-icon.png" style="height: 40px;" /></a></div></div>
    <div class="main-container">
      <div class="container">
        <div class="row">
          <div class="span12">
            <ul class="breadcrumb">           
              <li>
                 <span class="divider">|</span> <a href="testkit-example.html">TestKit Example (Scala)</a> <span class="divider">»</span>
              </li>
              <li>
                <a href="../index.html">Contents</a>
              </li>
              <li>
                <span class="divider">«</span> <a href="io.html">IO (Scala)</a> <span class="divider">|</span>
              </li>
              <li>
                Version 2.0.1
              </li>
            </ul>         
          </div>
        </div>
        <div class="row">
          <div class="span9">
            
  <div class="section" id="testing-actor-systems-scala">
<span id="akka-testkit"></span><h1>Testing Actor Systems (Scala)</h1>
<div class="toctree-wrapper compound">
<ul>
<li class="toctree-l1"><a class="reference internal" href="testkit-example.html">TestKit Example (Scala)</a></li>
</ul>
</div>
<p>As with any piece of software, automated tests are a very important part of the
development cycle. The actor model presents a different view on how units of
code are delimited and how they interact, which has an influence on how to
perform tests.</p>
<p>Akka comes with a dedicated module <tt class="xref py py-mod docutils literal"><span class="pre">akka-testkit</span></tt> for supporting tests at
different levels, which fall into two clearly distinct categories:</p>
<blockquote>
<div><ul class="simple">
<li>Testing isolated pieces of code without involving the actor model, meaning
without multiple threads; this implies completely deterministic behavior
concerning the ordering of events and no concurrency concerns and will be
called <strong>Unit Testing</strong> in the following.</li>
<li>Testing (multiple) encapsulated actors including multi-threaded scheduling;
this implies non-deterministic order of events but shielding from
concurrency concerns by the actor model and will be called <strong>Integration
Testing</strong> in the following.</li>
</ul>
</div></blockquote>
<p>There are of course variations on the granularity of tests in both categories,
where unit testing reaches down to white-box tests and integration testing can
encompass functional tests of complete actor networks. The important
distinction lies in whether concurrency concerns are part of the test or not.
The tools offered are described in detail in the following sections.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Be sure to add the module <tt class="xref py py-mod docutils literal"><span class="pre">akka-testkit</span></tt> to your dependencies.</p>
</div>
<div class="section" id="unit-testing-with-testactorref">
<h2>Unit Testing with <tt class="xref py py-class docutils literal"><span class="pre">TestActorRef</span></tt></h2>
<p>Testing the business logic inside <tt class="xref py py-class docutils literal"><span class="pre">Actor</span></tt> classes can be divided into
two parts: first, each atomic operation must work in isolation, then sequences
of incoming events must be processed correctly, even in the presence of some
possible variability in the ordering of events. The former is the primary use
case for single-threaded unit testing, while the latter can only be verified in
integration tests.</p>
<p>Normally, the <tt class="xref py py-class docutils literal"><span class="pre">ActorRef</span></tt> shields the underlying <tt class="xref py py-class docutils literal"><span class="pre">Actor</span></tt> instance
from the outside, the only communications channel is the actor&#8217;s mailbox. This
restriction is an impediment to unit testing, which led to the inception of the
<tt class="xref py py-class docutils literal"><span class="pre">TestActorRef</span></tt>. This special type of reference is designed specifically
for test purposes and allows access to the actor in two ways: either by
obtaining a reference to the underlying actor instance, or by invoking or
querying the actor&#8217;s behaviour (<tt class="xref py py-meth docutils literal"><span class="pre">receive</span></tt>). Each one warrants its own
section below.</p>
<div class="section" id="obtaining-a-reference-to-an-actor">
<h3>Obtaining a Reference to an <tt class="xref py py-class docutils literal"><span class="pre">Actor</span></tt></h3>
<p>Having access to the actual <tt class="xref py py-class docutils literal"><span class="pre">Actor</span></tt> object allows application of all
traditional unit testing techniques on the contained methods. Obtaining a
reference is done like this:</p>
<div class="highlight-scala"><div class="highlight"><pre><span class="k">import</span> <span class="nn">akka.testkit.TestActorRef</span>

<span class="k">val</span> <span class="n">actorRef</span> <span class="k">=</span> <span class="nc">TestActorRef</span><span class="o">[</span><span class="kt">MyActor</span><span class="o">]</span>
<span class="k">val</span> <span class="n">actor</span> <span class="k">=</span> <span class="n">actorRef</span><span class="o">.</span><span class="n">underlyingActor</span>
</pre></div>
</div>
<p>Since <tt class="xref py py-class docutils literal"><span class="pre">TestActorRef</span></tt> is generic in the actor type it returns the
underlying actor with its proper static type. From this point on you may bring
any unit testing tool to bear on your actor as usual.</p>
</div>
<div class="section" id="expecting-exceptions">
<h3>Expecting Exceptions</h3>
<p>Testing that an expected exception is thrown while processing a message sent to
the actor under test can be done by using a <tt class="xref py py-class docutils literal"><span class="pre">TestActorRef</span></tt> <tt class="xref py py-meth docutils literal"><span class="pre">receive</span></tt> based
invocation:</p>
<div class="highlight-scala"><div class="highlight"><pre><span class="k">import</span> <span class="nn">akka.testkit.TestActorRef</span>

<span class="k">val</span> <span class="n">actorRef</span> <span class="k">=</span> <span class="nc">TestActorRef</span><span class="o">(</span><span class="k">new</span> <span class="nc">Actor</span> <span class="o">{</span>
  <span class="k">def</span> <span class="n">receive</span> <span class="k">=</span> <span class="o">{</span>
    <span class="k">case</span> <span class="n">boom</span> <span class="k">⇒</span> <span class="k">throw</span> <span class="k">new</span> <span class="nc">IllegalArgumentException</span><span class="o">(</span><span class="s">&quot;boom&quot;</span><span class="o">)</span>
  <span class="o">}</span>
<span class="o">})</span>
<span class="n">intercept</span><span class="o">[</span><span class="kt">IllegalArgumentException</span><span class="o">]</span> <span class="o">{</span> <span class="n">actorRef</span><span class="o">.</span><span class="n">receive</span><span class="o">(</span><span class="s">&quot;hello&quot;</span><span class="o">)</span> <span class="o">}</span>
</pre></div>
</div>
</div>
<div class="section" id="testing-finite-state-machines">
<span id="testfsmref"></span><h3>Testing Finite State Machines</h3>
<p>If your actor under test is a <tt class="xref py py-class docutils literal"><span class="pre">FSM</span></tt>, you may use the special
<tt class="xref py py-class docutils literal"><span class="pre">TestFSMRef</span></tt> which offers all features of a normal <tt class="xref py py-class docutils literal"><span class="pre">TestActorRef</span></tt>
and in addition allows access to the internal state:</p>
<div class="highlight-scala"><div class="highlight"><pre><span class="k">import</span> <span class="nn">akka.testkit.TestFSMRef</span>
<span class="k">import</span> <span class="nn">akka.actor.FSM</span>
<span class="k">import</span> <span class="nn">akka.util.duration._</span>

<span class="k">val</span> <span class="n">fsm</span> <span class="k">=</span> <span class="nc">TestFSMRef</span><span class="o">(</span><span class="k">new</span> <span class="nc">Actor</span> <span class="k">with</span> <span class="nc">FSM</span><span class="o">[</span><span class="kt">Int</span>, <span class="kt">String</span><span class="o">]</span> <span class="o">{</span>
  <span class="n">startWith</span><span class="o">(</span><span class="mi">1</span><span class="o">,</span> <span class="s">&quot;&quot;</span><span class="o">)</span>
  <span class="n">when</span><span class="o">(</span><span class="mi">1</span><span class="o">)</span> <span class="o">{</span>
    <span class="k">case</span> <span class="nc">Event</span><span class="o">(</span><span class="s">&quot;go&quot;</span><span class="o">,</span> <span class="n">_</span><span class="o">)</span> <span class="k">⇒</span> <span class="n">goto</span><span class="o">(</span><span class="mi">2</span><span class="o">)</span> <span class="n">using</span> <span class="s">&quot;go&quot;</span>
  <span class="o">}</span>
  <span class="n">when</span><span class="o">(</span><span class="mi">2</span><span class="o">)</span> <span class="o">{</span>
    <span class="k">case</span> <span class="nc">Event</span><span class="o">(</span><span class="s">&quot;back&quot;</span><span class="o">,</span> <span class="n">_</span><span class="o">)</span> <span class="k">⇒</span> <span class="n">goto</span><span class="o">(</span><span class="mi">1</span><span class="o">)</span> <span class="n">using</span> <span class="s">&quot;back&quot;</span>
  <span class="o">}</span>
<span class="o">})</span>

<span class="n">assert</span><span class="o">(</span><span class="n">fsm</span><span class="o">.</span><span class="n">stateName</span> <span class="o">==</span> <span class="mi">1</span><span class="o">)</span>
<span class="n">assert</span><span class="o">(</span><span class="n">fsm</span><span class="o">.</span><span class="n">stateData</span> <span class="o">==</span> <span class="s">&quot;&quot;</span><span class="o">)</span>
<span class="n">fsm</span> <span class="o">!</span> <span class="s">&quot;go&quot;</span> <span class="c1">// being a TestActorRef, this runs also on the CallingThreadDispatcher</span>
<span class="n">assert</span><span class="o">(</span><span class="n">fsm</span><span class="o">.</span><span class="n">stateName</span> <span class="o">==</span> <span class="mi">2</span><span class="o">)</span>
<span class="n">assert</span><span class="o">(</span><span class="n">fsm</span><span class="o">.</span><span class="n">stateData</span> <span class="o">==</span> <span class="s">&quot;go&quot;</span><span class="o">)</span>

<span class="n">fsm</span><span class="o">.</span><span class="n">setState</span><span class="o">(</span><span class="n">stateName</span> <span class="k">=</span> <span class="mi">1</span><span class="o">)</span>
<span class="n">assert</span><span class="o">(</span><span class="n">fsm</span><span class="o">.</span><span class="n">stateName</span> <span class="o">==</span> <span class="mi">1</span><span class="o">)</span>

<span class="n">assert</span><span class="o">(</span><span class="n">fsm</span><span class="o">.</span><span class="n">timerActive_?</span><span class="o">(</span><span class="s">&quot;test&quot;</span><span class="o">)</span> <span class="o">==</span> <span class="kc">false</span><span class="o">)</span>
<span class="n">fsm</span><span class="o">.</span><span class="n">setTimer</span><span class="o">(</span><span class="s">&quot;test&quot;</span><span class="o">,</span> <span class="mi">12</span><span class="o">,</span> <span class="mi">10</span> <span class="n">millis</span><span class="o">,</span> <span class="kc">true</span><span class="o">)</span>
<span class="n">assert</span><span class="o">(</span><span class="n">fsm</span><span class="o">.</span><span class="n">timerActive_?</span><span class="o">(</span><span class="s">&quot;test&quot;</span><span class="o">)</span> <span class="o">==</span> <span class="kc">true</span><span class="o">)</span>
<span class="n">fsm</span><span class="o">.</span><span class="n">cancelTimer</span><span class="o">(</span><span class="s">&quot;test&quot;</span><span class="o">)</span>
<span class="n">assert</span><span class="o">(</span><span class="n">fsm</span><span class="o">.</span><span class="n">timerActive_?</span><span class="o">(</span><span class="s">&quot;test&quot;</span><span class="o">)</span> <span class="o">==</span> <span class="kc">false</span><span class="o">)</span>
</pre></div>
</div>
<p>Due to a limitation in Scala’s type inference, there is only the factory method
shown above, so you will probably write code like <tt class="docutils literal"><span class="pre">TestFSMRef(new</span> <span class="pre">MyFSM)</span></tt>
instead of the hypothetical <tt class="xref py py-class docutils literal"><span class="pre">ActorRef</span></tt>-inspired <tt class="docutils literal"><span class="pre">TestFSMRef[MyFSM]</span></tt>.
All methods shown above directly access the FSM state without any
synchronization; this is perfectly alright if the
<tt class="xref py py-class docutils literal"><span class="pre">CallingThreadDispatcher</span></tt> is used (which is the default for
<tt class="xref py py-class docutils literal"><span class="pre">TestFSMRef</span></tt>) and no other threads are involved, but it may lead to
surprises if you were to actually exercise timer events, because those are
executed on the <tt class="xref py py-obj docutils literal"><span class="pre">Scheduler</span></tt> thread.</p>
</div>
<div class="section" id="testing-the-actor-s-behavior">
<h3>Testing the Actor&#8217;s Behavior</h3>
<p>When the dispatcher invokes the processing behavior of an actor on a message,
it actually calls <tt class="xref py py-meth docutils literal"><span class="pre">apply</span></tt> on the current behavior registered for the
actor. This starts out with the return value of the declared <tt class="xref py py-meth docutils literal"><span class="pre">receive</span></tt>
method, but it may also be changed using <tt class="xref py py-meth docutils literal"><span class="pre">become</span></tt> and <tt class="xref py py-meth docutils literal"><span class="pre">unbecome</span></tt> in
response to external messages. All of this contributes to the overall actor
behavior and it does not lend itself to easy testing on the <tt class="xref py py-class docutils literal"><span class="pre">Actor</span></tt>
itself. Therefore the <tt class="xref py py-class docutils literal"><span class="pre">TestActorRef</span></tt> offers a different mode of
operation to complement the <tt class="xref py py-class docutils literal"><span class="pre">Actor</span></tt> testing: it supports all operations
also valid on normal <tt class="xref py py-class docutils literal"><span class="pre">ActorRef</span></tt>. Messages sent to the actor are
processed synchronously on the current thread and answers may be sent back as
usual. This trick is made possible by the <tt class="xref py py-class docutils literal"><span class="pre">CallingThreadDispatcher</span></tt>
described below; this dispatcher is set implicitly for any actor instantiated
into a <tt class="xref py py-class docutils literal"><span class="pre">TestActorRef</span></tt>.</p>
<div class="highlight-scala"><div class="highlight"><pre><span class="k">import</span> <span class="nn">akka.testkit.TestActorRef</span>
<span class="k">import</span> <span class="nn">akka.util.duration._</span>
<span class="k">import</span> <span class="nn">akka.dispatch.Await</span>
<span class="k">import</span> <span class="nn">akka.pattern.ask</span>

<span class="k">val</span> <span class="n">actorRef</span> <span class="k">=</span> <span class="nc">TestActorRef</span><span class="o">(</span><span class="k">new</span> <span class="nc">MyActor</span><span class="o">)</span>
<span class="c1">// hypothetical message stimulating a &#39;42&#39; answer</span>
<span class="k">val</span> <span class="n">result</span> <span class="k">=</span> <span class="nc">Await</span><span class="o">.</span><span class="n">result</span><span class="o">((</span><span class="n">actorRef</span> <span class="o">?</span> <span class="nc">Say42</span><span class="o">),</span> <span class="mi">5</span> <span class="n">seconds</span><span class="o">).</span><span class="n">asInstanceOf</span><span class="o">[</span><span class="kt">Int</span><span class="o">]</span>
<span class="n">result</span> <span class="n">must</span> <span class="n">be</span><span class="o">(</span><span class="mi">42</span><span class="o">)</span>
</pre></div>
</div>
<p>As the <tt class="xref py py-class docutils literal"><span class="pre">TestActorRef</span></tt> is a subclass of <tt class="xref py py-class docutils literal"><span class="pre">LocalActorRef</span></tt> with a few
special extras, also aspects like supervision and restarting work properly, but
beware that execution is only strictly synchronous as long as all actors
involved use the <tt class="xref py py-class docutils literal"><span class="pre">CallingThreadDispatcher</span></tt>. As soon as you add elements
which include more sophisticated scheduling you leave the realm of unit testing
as you then need to think about asynchronicity again (in most cases the problem
will be to wait until the desired effect had a chance to happen).</p>
<p>One more special aspect which is overridden for single-threaded tests is the
<tt class="xref py py-meth docutils literal"><span class="pre">receiveTimeout</span></tt>, as including that would entail asynchronous queuing of
<tt class="xref py py-obj docutils literal"><span class="pre">ReceiveTimeout</span></tt> messages, violating the synchronous contract.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">To summarize: <tt class="xref py py-class docutils literal"><span class="pre">TestActorRef</span></tt> overwrites two fields: it sets the
dispatcher to <tt class="xref py py-obj docutils literal"><span class="pre">CallingThreadDispatcher.global</span></tt> and it sets the
<tt class="xref py py-obj docutils literal"><span class="pre">receiveTimeout</span></tt> to None.</p>
</div>
</div>
<div class="section" id="the-way-in-between">
<h3>The Way In-Between</h3>
<p>If you want to test the actor behavior, including hotswapping, but without
involving a dispatcher and without having the <tt class="xref py py-class docutils literal"><span class="pre">TestActorRef</span></tt> swallow
any thrown exceptions, then there is another mode available for you: just use
the <tt class="xref py py-meth docutils literal"><span class="pre">receive</span></tt> method <tt class="xref py py-class docutils literal"><span class="pre">TestActorRef</span></tt>, which will be forwarded to the
underlying actor:</p>
<div class="highlight-scala"><div class="highlight"><pre><span class="k">import</span> <span class="nn">akka.testkit.TestActorRef</span>
<span class="n">system</span><span class="o">.</span><span class="n">eventStream</span><span class="o">.</span><span class="n">subscribe</span><span class="o">(</span><span class="n">testActor</span><span class="o">,</span> <span class="n">classOf</span><span class="o">[</span><span class="kt">UnhandledMessage</span><span class="o">])</span>
<span class="k">val</span> <span class="n">ref</span> <span class="k">=</span> <span class="nc">TestActorRef</span><span class="o">[</span><span class="kt">MyActor</span><span class="o">]</span>
<span class="n">ref</span><span class="o">.</span><span class="n">receive</span><span class="o">(</span><span class="nc">Unknown</span><span class="o">)</span>
<span class="n">expectMsg</span><span class="o">(</span><span class="mi">1</span> <span class="n">second</span><span class="o">,</span> <span class="nc">UnhandledMessage</span><span class="o">(</span><span class="nc">Unknown</span><span class="o">,</span> <span class="n">system</span><span class="o">.</span><span class="n">deadLetters</span><span class="o">,</span> <span class="n">ref</span><span class="o">))</span>
</pre></div>
</div>
<p>The above sample assumes the default behavior for unhandled messages, i.e.
that the actor doesn&#8217;t swallow all messages and doesn&#8217;t override <tt class="xref py py-meth docutils literal"><span class="pre">unhandled</span></tt>.</p>
</div>
<div class="section" id="use-cases">
<h3>Use Cases</h3>
<p>You may of course mix and match both modi operandi of <tt class="xref py py-class docutils literal"><span class="pre">TestActorRef</span></tt> as
suits your test needs:</p>
<blockquote>
<div><ul class="simple">
<li>one common use case is setting up the actor into a specific internal state
before sending the test message</li>
<li>another is to verify correct internal state transitions after having sent
the test message</li>
</ul>
</div></blockquote>
<p>Feel free to experiment with the possibilities, and if you find useful
patterns, don&#8217;t hesitate to let the Akka forums know about them! Who knows,
common operations might even be worked into nice DSLs.</p>
</div>
</div>
<div class="section" id="integration-testing-with-testkit">
<h2>Integration Testing with <tt class="xref py py-class docutils literal"><span class="pre">TestKit</span></tt></h2>
<p>When you are reasonably sure that your actor&#8217;s business logic is correct, the
next step is verifying that it works correctly within its intended environment
(if the individual actors are simple enough, possibly because they use the
<tt class="xref py py-mod docutils literal"><span class="pre">FSM</span></tt> module, this might also be the first step). The definition of the
environment depends of course very much on the problem at hand and the level at
which you intend to test, ranging for functional/integration tests to full
system tests. The minimal setup consists of the test procedure, which provides
the desired stimuli, the actor under test, and an actor receiving replies.
Bigger systems replace the actor under test with a network of actors, apply
stimuli at varying injection points and arrange results to be sent from
different emission points, but the basic principle stays the same in that a
single procedure drives the test.</p>
<p>The <tt class="xref py py-class docutils literal"><span class="pre">TestKit</span></tt> class contains a collection of tools which makes this
common task easy.</p>
<div class="highlight-scala"><div class="highlight"><pre><span class="k">import</span> <span class="nn">akka.actor.ActorSystem</span>
<span class="k">import</span> <span class="nn">akka.actor.Actor</span>
<span class="k">import</span> <span class="nn">akka.actor.Props</span>
<span class="k">import</span> <span class="nn">akka.testkit.TestKit</span>
<span class="k">import</span> <span class="nn">org.scalatest.WordSpec</span>
<span class="k">import</span> <span class="nn">org.scalatest.matchers.MustMatchers</span>
<span class="k">import</span> <span class="nn">org.scalatest.BeforeAndAfterAll</span>
<span class="k">import</span> <span class="nn">akka.testkit.ImplicitSender</span>

<span class="k">object</span> <span class="nc">MySpec</span> <span class="o">{</span>
  <span class="k">class</span> <span class="nc">EchoActor</span> <span class="k">extends</span> <span class="nc">Actor</span> <span class="o">{</span>
    <span class="k">def</span> <span class="n">receive</span> <span class="k">=</span> <span class="o">{</span>
      <span class="k">case</span> <span class="n">x</span> <span class="k">⇒</span> <span class="n">sender</span> <span class="o">!</span> <span class="n">x</span>
    <span class="o">}</span>
  <span class="o">}</span>
<span class="o">}</span>

<span class="k">class</span> <span class="nc">MySpec</span><span class="o">(</span><span class="nc">_system</span><span class="k">:</span> <span class="kt">ActorSystem</span><span class="o">)</span> <span class="k">extends</span> <span class="nc">TestKit</span><span class="o">(</span><span class="nc">_system</span><span class="o">)</span> <span class="k">with</span> <span class="nc">ImplicitSender</span>
  <span class="k">with</span> <span class="nc">WordSpec</span> <span class="k">with</span> <span class="nc">MustMatchers</span> <span class="k">with</span> <span class="nc">BeforeAndAfterAll</span> <span class="o">{</span>

  <span class="k">def</span> <span class="k">this</span><span class="o">()</span> <span class="k">=</span> <span class="k">this</span><span class="o">(</span><span class="nc">ActorSystem</span><span class="o">(</span><span class="s">&quot;MySpec&quot;</span><span class="o">))</span>

  <span class="k">import</span> <span class="nn">MySpec._</span>

  <span class="k">override</span> <span class="k">def</span> <span class="n">afterAll</span> <span class="o">{</span>
    <span class="n">system</span><span class="o">.</span><span class="n">shutdown</span><span class="o">()</span>
  <span class="o">}</span>

  <span class="s">&quot;An Echo actor&quot;</span> <span class="n">must</span> <span class="o">{</span>

    <span class="s">&quot;send back messages unchanged&quot;</span> <span class="n">in</span> <span class="o">{</span>
      <span class="k">val</span> <span class="n">echo</span> <span class="k">=</span> <span class="n">system</span><span class="o">.</span><span class="n">actorOf</span><span class="o">(</span><span class="nc">Props</span><span class="o">[</span><span class="kt">EchoActor</span><span class="o">])</span>
      <span class="n">echo</span> <span class="o">!</span> <span class="s">&quot;hello world&quot;</span>
      <span class="n">expectMsg</span><span class="o">(</span><span class="s">&quot;hello world&quot;</span><span class="o">)</span>
    <span class="o">}</span>

  <span class="o">}</span>
<span class="o">}</span>
</pre></div>
</div>
<p>The <tt class="xref py py-class docutils literal"><span class="pre">TestKit</span></tt> contains an actor named <tt class="xref py py-obj docutils literal"><span class="pre">testActor</span></tt> which is the
entry point for messages to be examined with the various <tt class="docutils literal"><span class="pre">expectMsg...</span></tt>
assertions detailed below. When mixing in the trait <tt class="docutils literal"><span class="pre">ImplicitSender</span></tt> this
test actor is implicitly used as sender reference when dispatching messages
from the test procedure. The <tt class="xref py py-obj docutils literal"><span class="pre">testActor</span></tt> may also be passed to
other actors as usual, usually subscribing it as notification listener. There
is a whole set of examination methods, e.g. receiving all consecutive messages
matching certain criteria, receiving a whole sequence of fixed messages or
classes, receiving nothing for some time, etc.</p>
<p>Remember to shut down the actor system after the test is finished (also in case
of failure) so that all actors—including the test actor—are stopped.</p>
<div class="section" id="built-in-assertions">
<h3>Built-In Assertions</h3>
<p>The above mentioned <tt class="xref py py-meth docutils literal"><span class="pre">expectMsg</span></tt> is not the only method for formulating
assertions concerning received messages. Here is the full list:</p>
<blockquote>
<div><ul>
<li><p class="first"><tt class="xref py py-meth docutils literal"><span class="pre">expectMsg[T](d:</span> <span class="pre">Duration,</span> <span class="pre">msg:</span> <span class="pre">T):</span> <span class="pre">T</span></tt></p>
<p>The given message object must be received within the specified time; the
object will be returned.</p>
</li>
<li><p class="first"><tt class="xref py py-meth docutils literal"><span class="pre">expectMsgPF[T](d:</span> <span class="pre">Duration)(pf:</span> <span class="pre">PartialFunction[Any,</span> <span class="pre">T]):</span> <span class="pre">T</span></tt></p>
<p>Within the given time period, a message must be received and the given
partial function must be defined for that message; the result from applying
the partial function to the received message is returned. The duration may
be left unspecified (empty parentheses are required in this case) to use
the deadline from the innermost enclosing <a class="reference internal" href="#testkit-within"><em>within</em></a>
block instead.</p>
</li>
<li><p class="first"><tt class="xref py py-meth docutils literal"><span class="pre">expectMsgClass[T](d:</span> <span class="pre">Duration,</span> <span class="pre">c:</span> <span class="pre">Class[T]):</span> <span class="pre">T</span></tt></p>
<p>An object which is an instance of the given <tt class="xref py py-class docutils literal"><span class="pre">Class</span></tt> must be received
within the allotted time frame; the object will be returned. Note that this
does a conformance check; if you need the class to be equal, have a look at
<tt class="xref py py-meth docutils literal"><span class="pre">expectMsgAllClassOf</span></tt> with a single given class argument.</p>
</li>
<li><p class="first"><tt class="xref py py-meth docutils literal"><span class="pre">expectMsgType[T:</span> <span class="pre">Manifest](d:</span> <span class="pre">Duration)</span></tt></p>
<p>An object which is an instance of the given type (after erasure) must be
received within the allotted time frame; the object will be returned. This
method is approximately equivalent to
<tt class="docutils literal"><span class="pre">expectMsgClass(manifest[T].erasure)</span></tt>.</p>
</li>
<li><p class="first"><tt class="xref py py-meth docutils literal"><span class="pre">expectMsgAnyOf[T](d:</span> <span class="pre">Duration,</span> <span class="pre">obj:</span> <span class="pre">T*):</span> <span class="pre">T</span></tt></p>
<p>An object must be received within the given time, and it must be equal (
compared with <tt class="docutils literal"><span class="pre">==</span></tt>) to at least one of the passed reference objects; the
received object will be returned.</p>
</li>
<li><p class="first"><tt class="xref py py-meth docutils literal"><span class="pre">expectMsgAnyClassOf[T](d:</span> <span class="pre">Duration,</span> <span class="pre">obj:</span> <span class="pre">Class[_</span> <span class="pre">&lt;:</span> <span class="pre">T]*):</span> <span class="pre">T</span></tt></p>
<p>An object must be received within the given time, and it must be an
instance of at least one of the supplied <tt class="xref py py-class docutils literal"><span class="pre">Class</span></tt> objects; the
received object will be returned.</p>
</li>
<li><p class="first"><tt class="xref py py-meth docutils literal"><span class="pre">expectMsgAllOf[T](d:</span> <span class="pre">Duration,</span> <span class="pre">obj:</span> <span class="pre">T*):</span> <span class="pre">Seq[T]</span></tt></p>
<p>A number of objects matching the size of the supplied object array must be
received within the given time, and for each of the given objects there
must exist at least one among the received ones which equals (compared with
<tt class="docutils literal"><span class="pre">==</span></tt>) it. The full sequence of received objects is returned.</p>
</li>
<li><p class="first"><tt class="xref py py-meth docutils literal"><span class="pre">expectMsgAllClassOf[T](d:</span> <span class="pre">Duration,</span> <span class="pre">c:</span> <span class="pre">Class[_</span> <span class="pre">&lt;:</span> <span class="pre">T]*):</span> <span class="pre">Seq[T]</span></tt></p>
<p>A number of objects matching the size of the supplied <tt class="xref py py-class docutils literal"><span class="pre">Class</span></tt> array
must be received within the given time, and for each of the given classes
there must exist at least one among the received objects whose class equals
(compared with <tt class="docutils literal"><span class="pre">==</span></tt>) it (this is <em>not</em> a conformance check). The full
sequence of received objects is returned.</p>
</li>
<li><p class="first"><tt class="xref py py-meth docutils literal"><span class="pre">expectMsgAllConformingOf[T](d:</span> <span class="pre">Duration,</span> <span class="pre">c:</span> <span class="pre">Class[_</span> <span class="pre">&lt;:</span> <span class="pre">T]*):</span> <span class="pre">Seq[T]</span></tt></p>
<p>A number of objects matching the size of the supplied <tt class="xref py py-class docutils literal"><span class="pre">Class</span></tt> array
must be received within the given time, and for each of the given classes
there must exist at least one among the received objects which is an
instance of this class. The full sequence of received objects is returned.</p>
</li>
<li><p class="first"><tt class="xref py py-meth docutils literal"><span class="pre">expectNoMsg(d:</span> <span class="pre">Duration)</span></tt></p>
<p>No message must be received within the given time. This also fails if a
message has been received before calling this method which has not been
removed from the queue using one of the other methods.</p>
</li>
<li><p class="first"><tt class="xref py py-meth docutils literal"><span class="pre">receiveN(n:</span> <span class="pre">Int,</span> <span class="pre">d:</span> <span class="pre">Duration):</span> <span class="pre">Seq[AnyRef]</span></tt></p>
<p><tt class="docutils literal"><span class="pre">n</span></tt> messages must be received within the given time; the received
messages are returned.</p>
</li>
<li><p class="first"><tt class="xref py py-meth docutils literal"><span class="pre">fishForMessage(max:</span> <span class="pre">Duration,</span> <span class="pre">hint:</span> <span class="pre">String)(pf:</span> <span class="pre">PartialFunction[Any,</span> <span class="pre">Boolean]):</span> <span class="pre">Any</span></tt></p>
<p>Keep receiving messages as long as the time is not used up and the partial
function matches and returns <tt class="docutils literal"><span class="pre">false</span></tt>. Returns the message received for
which it returned <tt class="docutils literal"><span class="pre">true</span></tt> or throws an exception, which will include the
provided hint for easier debugging.</p>
</li>
</ul>
</div></blockquote>
<p>In addition to message reception assertions there are also methods which help
with message flows:</p>
<blockquote>
<div><ul>
<li><p class="first"><tt class="xref py py-meth docutils literal"><span class="pre">receiveOne(d:</span> <span class="pre">Duration):</span> <span class="pre">AnyRef</span></tt></p>
<p>Tries to receive one message for at most the given time interval and
returns <tt class="docutils literal"><span class="pre">null</span></tt> in case of failure. If the given Duration is zero, the
call is non-blocking (polling mode).</p>
</li>
<li><p class="first"><tt class="xref py py-meth docutils literal"><span class="pre">receiveWhile[T](max:</span> <span class="pre">Duration,</span> <span class="pre">idle:</span> <span class="pre">Duration,</span> <span class="pre">messages:</span> <span class="pre">Int)(pf:</span> <span class="pre">PartialFunction[Any,</span> <span class="pre">T]):</span> <span class="pre">Seq[T]</span></tt></p>
<p>Collect messages as long as</p>
<ul class="simple">
<li>they are matching the given partial function</li>
<li>the given time interval is not used up</li>
<li>the next message is received within the idle timeout</li>
<li>the number of messages has not yet reached the maximum</li>
</ul>
<p>All collected messages are returned. The maximum duration defaults to the
time remaining in the innermost enclosing <a class="reference internal" href="#testkit-within"><em>within</em></a>
block and the idle duration defaults to infinity (thereby disabling the
idle timeout feature). The number of expected messages defaults to
<tt class="docutils literal"><span class="pre">Int.MaxValue</span></tt>, which effectively disables this limit.</p>
</li>
<li><p class="first"><tt class="xref py py-meth docutils literal"><span class="pre">awaitCond(p:</span> <span class="pre">=&gt;</span> <span class="pre">Boolean,</span> <span class="pre">max:</span> <span class="pre">Duration,</span> <span class="pre">interval:</span> <span class="pre">Duration)</span></tt></p>
<p>Poll the given condition every <tt class="xref py py-obj docutils literal"><span class="pre">interval</span></tt> until it returns <tt class="docutils literal"><span class="pre">true</span></tt> or
the <tt class="xref py py-obj docutils literal"><span class="pre">max</span></tt> duration is used up. The interval defaults to 100 ms and the
maximum defaults to the time remaining in the innermost enclosing
<a class="reference internal" href="#testkit-within"><em>within</em></a> block.</p>
</li>
<li><p class="first"><tt class="xref py py-meth docutils literal"><span class="pre">ignoreMsg(pf:</span> <span class="pre">PartialFunction[AnyRef,</span> <span class="pre">Boolean])</span></tt></p>
<p><tt class="xref py py-meth docutils literal"><span class="pre">ignoreNoMsg</span></tt></p>
<p>The internal <tt class="xref py py-obj docutils literal"><span class="pre">testActor</span></tt> contains a partial function for ignoring
messages: it will only enqueue messages which do not match the function or
for which the function returns <tt class="docutils literal"><span class="pre">false</span></tt>. This function can be set and
reset using the methods given above; each invocation replaces the previous
function, they are not composed.</p>
<p>This feature is useful e.g. when testing a logging system, where you want
to ignore regular messages and are only interested in your specific ones.</p>
</li>
</ul>
</div></blockquote>
</div>
<div class="section" id="id1">
<h3>Expecting Exceptions</h3>
<p>Since an integration test does not allow to the internal processing of the
participating actors, verifying expected exceptions cannot be done directly.
Instead, use the logging system for this purpose: replacing the normal event
handler with the <tt class="xref py py-class docutils literal"><span class="pre">TestEventListener</span></tt> and using an <tt class="xref py py-class docutils literal"><span class="pre">EventFilter</span></tt>
allows assertions on log messages, including those which are generated by
exceptions:</p>
<div class="highlight-scala"><div class="highlight"><pre><span class="k">import</span> <span class="nn">akka.testkit.EventFilter</span>
<span class="k">import</span> <span class="nn">com.typesafe.config.ConfigFactory</span>

<span class="k">implicit</span> <span class="k">val</span> <span class="n">system</span> <span class="k">=</span> <span class="nc">ActorSystem</span><span class="o">(</span><span class="s">&quot;testsystem&quot;</span><span class="o">,</span> <span class="nc">ConfigFactory</span><span class="o">.</span><span class="n">parseString</span><span class="o">(</span><span class="s">&quot;&quot;&quot;</span>
<span class="s">  akka.event-handlers = [&quot;akka.testkit.TestEventListener&quot;]</span>
<span class="s">  &quot;&quot;&quot;</span><span class="o">))</span>
<span class="k">try</span> <span class="o">{</span>
  <span class="k">val</span> <span class="n">actor</span> <span class="k">=</span> <span class="n">system</span><span class="o">.</span><span class="n">actorOf</span><span class="o">(</span><span class="nc">Props</span><span class="o">.</span><span class="n">empty</span><span class="o">)</span>
  <span class="nc">EventFilter</span><span class="o">[</span><span class="kt">ActorKilledException</span><span class="o">](</span><span class="n">occurrences</span> <span class="k">=</span> <span class="mi">1</span><span class="o">)</span> <span class="n">intercept</span> <span class="o">{</span>
    <span class="n">actor</span> <span class="o">!</span> <span class="nc">Kill</span>
  <span class="o">}</span>
<span class="o">}</span> <span class="k">finally</span> <span class="o">{</span>
  <span class="n">system</span><span class="o">.</span><span class="n">shutdown</span><span class="o">()</span>
<span class="o">}</span>
</pre></div>
</div>
</div>
<div class="section" id="timing-assertions">
<span id="testkit-within"></span><h3>Timing Assertions</h3>
<p>Another important part of functional testing concerns timing: certain events
must not happen immediately (like a timer), others need to happen before a
deadline. Therefore, all examination methods accept an upper time limit within
the positive or negative result must be obtained. Lower time limits need to be
checked external to the examination, which is facilitated by a new construct
for managing time constraints:</p>
<div class="highlight-scala"><div class="highlight"><pre><span class="n">within</span><span class="o">([</span><span class="kt">min</span>, <span class="o">]</span><span class="n">max</span><span class="o">)</span> <span class="o">{</span>
  <span class="o">...</span>
<span class="o">}</span>
</pre></div>
</div>
<p>The block given to <tt class="xref py py-meth docutils literal"><span class="pre">within</span></tt> must complete after a <a class="reference internal" href="../common/duration.html#duration"><em>Duration</em></a> which
is between <tt class="xref py py-obj docutils literal"><span class="pre">min</span></tt> and <tt class="xref py py-obj docutils literal"><span class="pre">max</span></tt>, where the former defaults to zero. The
deadline calculated by adding the <tt class="xref py py-obj docutils literal"><span class="pre">max</span></tt> parameter to the block&#8217;s start
time is implicitly available within the block to all examination methods, if
you do not specify it, is is inherited from the innermost enclosing
<tt class="xref py py-meth docutils literal"><span class="pre">within</span></tt> block.</p>
<p>It should be noted that if the last message-receiving assertion of the block is
<tt class="xref py py-meth docutils literal"><span class="pre">expectNoMsg</span></tt> or <tt class="xref py py-meth docutils literal"><span class="pre">receiveWhile</span></tt>, the final check of the
<tt class="xref py py-meth docutils literal"><span class="pre">within</span></tt> is skipped in order to avoid false positives due to wake-up
latencies. This means that while individual contained assertions still use the
maximum time bound, the overall block may take arbitrarily longer in this case.</p>
<div class="highlight-scala"><div class="highlight"><pre><span class="k">import</span> <span class="nn">akka.actor.Props</span>
<span class="k">import</span> <span class="nn">akka.util.duration._</span>

<span class="k">val</span> <span class="n">worker</span> <span class="k">=</span> <span class="n">system</span><span class="o">.</span><span class="n">actorOf</span><span class="o">(</span><span class="nc">Props</span><span class="o">[</span><span class="kt">Worker</span><span class="o">])</span>
<span class="n">within</span><span class="o">(</span><span class="mi">200</span> <span class="n">millis</span><span class="o">)</span> <span class="o">{</span>
  <span class="n">worker</span> <span class="o">!</span> <span class="s">&quot;some work&quot;</span>
  <span class="n">expectMsg</span><span class="o">(</span><span class="s">&quot;some result&quot;</span><span class="o">)</span>
  <span class="n">expectNoMsg</span> <span class="c1">// will block for the rest of the 200ms</span>
  <span class="nc">Thread</span><span class="o">.</span><span class="n">sleep</span><span class="o">(</span><span class="mi">300</span><span class="o">)</span> <span class="c1">// will NOT make this block fail</span>
<span class="o">}</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">All times are measured using <tt class="docutils literal"><span class="pre">System.nanoTime</span></tt>, meaning that they describe
wall time, not CPU time.</p>
</div>
<p>Ray Roestenburg has written a great article on using the TestKit:
<a class="reference external" href="http://roestenburg.agilesquad.com/2011/02/unit-testing-akka-actors-with-testkit_12.html">http://roestenburg.agilesquad.com/2011/02/unit-testing-akka-actors-with-testkit_12.html</a>.
His full example is also available <a class="reference internal" href="testkit-example.html#testkit-example"><em>here</em></a>.</p>
<div class="section" id="accounting-for-slow-test-systems">
<h4>Accounting for Slow Test Systems</h4>
<p>The tight timeouts you use during testing on your lightning-fast notebook will
invariably lead to spurious test failures on the heavily loaded Jenkins server
(or similar). To account for this situation, all maximum durations are
internally scaled by a factor taken from the <a class="reference internal" href="../general/configuration.html#configuration"><em>Configuration</em></a>,
<tt class="docutils literal"><span class="pre">akka.test.timefactor</span></tt>, which defaults to 1.</p>
<p>You can scale other durations with the same factor by using the implicit conversion
in <tt class="docutils literal"><span class="pre">akka.testkit</span></tt> package object to add dilated function to <tt class="xref py py-class docutils literal"><span class="pre">Duration</span></tt>.</p>
<div class="highlight-scala"><div class="highlight"><pre><span class="k">import</span> <span class="nn">akka.util.duration._</span>
<span class="k">import</span> <span class="nn">akka.testkit._</span>
<span class="mf">10.</span><span class="n">milliseconds</span><span class="o">.</span><span class="n">dilated</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="resolving-conflicts-with-implicit-actorref">
<h3>Resolving Conflicts with Implicit ActorRef</h3>
<p>If you want the sender of messages inside your TestKit-based tests to be the <tt class="docutils literal"><span class="pre">testActor</span></tt>
simply mix in <tt class="docutils literal"><span class="pre">ÌmplicitSender</span></tt> into your test.</p>
<div class="highlight-scala"><div class="highlight"><pre><span class="k">class</span> <span class="nc">MySpec</span><span class="o">(</span><span class="nc">_system</span><span class="k">:</span> <span class="kt">ActorSystem</span><span class="o">)</span> <span class="k">extends</span> <span class="nc">TestKit</span><span class="o">(</span><span class="nc">_system</span><span class="o">)</span> <span class="k">with</span> <span class="nc">ImplicitSender</span>
  <span class="k">with</span> <span class="nc">WordSpec</span> <span class="k">with</span> <span class="nc">MustMatchers</span> <span class="k">with</span> <span class="nc">BeforeAndAfterAll</span> <span class="o">{</span>
</pre></div>
</div>
</div>
<div class="section" id="using-multiple-probe-actors">
<h3>Using Multiple Probe Actors</h3>
<p>When the actors under test are supposed to send various messages to different
destinations, it may be difficult distinguishing the message streams arriving
at the <tt class="xref py py-obj docutils literal"><span class="pre">testActor</span></tt> when using the <tt class="xref py py-class docutils literal"><span class="pre">TestKit</span></tt> as a mixin. Another
approach is to use it for creation of simple probe actors to be inserted in the
message flows. To make this more powerful and convenient, there is a concrete
implementation called <tt class="xref py py-class docutils literal"><span class="pre">TestProbe</span></tt>. The functionality is best explained
using a small example:</p>
<div class="highlight-scala"><div class="highlight"><pre><span class="k">import</span> <span class="nn">akka.testkit.TestProbe</span>
<span class="k">import</span> <span class="nn">akka.util.duration._</span>
<span class="k">import</span> <span class="nn">akka.actor._</span>
<span class="k">import</span> <span class="nn">akka.dispatch.Futures</span>

  <span class="k">class</span> <span class="nc">MyDoubleEcho</span> <span class="k">extends</span> <span class="nc">Actor</span> <span class="o">{</span>
    <span class="k">var</span> <span class="n">dest1</span><span class="k">:</span> <span class="kt">ActorRef</span> <span class="o">=</span> <span class="k">_</span>
    <span class="k">var</span> <span class="n">dest2</span><span class="k">:</span> <span class="kt">ActorRef</span> <span class="o">=</span> <span class="k">_</span>
    <span class="k">def</span> <span class="n">receive</span> <span class="k">=</span> <span class="o">{</span>
      <span class="k">case</span> <span class="o">(</span><span class="n">d1</span><span class="k">:</span> <span class="kt">ActorRef</span><span class="o">,</span> <span class="n">d2</span><span class="k">:</span> <span class="kt">ActorRef</span><span class="o">)</span> <span class="k">⇒</span>
        <span class="n">dest1</span> <span class="k">=</span> <span class="n">d1</span>
        <span class="n">dest2</span> <span class="k">=</span> <span class="n">d2</span>
      <span class="k">case</span> <span class="n">x</span> <span class="k">⇒</span>
        <span class="n">dest1</span> <span class="o">!</span> <span class="n">x</span>
        <span class="n">dest2</span> <span class="o">!</span> <span class="n">x</span>
    <span class="o">}</span>
  <span class="o">}</span>

    <span class="k">val</span> <span class="n">probe1</span> <span class="k">=</span> <span class="nc">TestProbe</span><span class="o">()</span>
    <span class="k">val</span> <span class="n">probe2</span> <span class="k">=</span> <span class="nc">TestProbe</span><span class="o">()</span>
    <span class="k">val</span> <span class="n">actor</span> <span class="k">=</span> <span class="n">system</span><span class="o">.</span><span class="n">actorOf</span><span class="o">(</span><span class="nc">Props</span><span class="o">[</span><span class="kt">MyDoubleEcho</span><span class="o">])</span>
    <span class="n">actor</span> <span class="o">!</span> <span class="o">(</span><span class="n">probe1</span><span class="o">.</span><span class="n">ref</span><span class="o">,</span> <span class="n">probe2</span><span class="o">.</span><span class="n">ref</span><span class="o">)</span>
    <span class="n">actor</span> <span class="o">!</span> <span class="s">&quot;hello&quot;</span>
    <span class="n">probe1</span><span class="o">.</span><span class="n">expectMsg</span><span class="o">(</span><span class="mi">500</span> <span class="n">millis</span><span class="o">,</span> <span class="s">&quot;hello&quot;</span><span class="o">)</span>
    <span class="n">probe2</span><span class="o">.</span><span class="n">expectMsg</span><span class="o">(</span><span class="mi">500</span> <span class="n">millis</span><span class="o">,</span> <span class="s">&quot;hello&quot;</span><span class="o">)</span>
</pre></div>
</div>
<p>Here a the system under test is simulated by <tt class="xref py py-class docutils literal"><span class="pre">MyDoubleEcho</span></tt>, which is
supposed to mirror its input to two outputs. Attaching two test probes enables
verification of the (simplistic) behavior. Another example would be two actors
A and B which collaborate by A sending messages to B. In order to verify this
message flow, a <tt class="xref py py-class docutils literal"><span class="pre">TestProbe</span></tt> could be inserted as target of A, using the
forwarding capabilities or auto-pilot described below to include a real B in
the test setup.</p>
<p>Probes may also be equipped with custom assertions to make your test code even
more concise and clear:</p>
<div class="highlight-scala"><div class="highlight"><pre><span class="k">case</span> <span class="k">class</span> <span class="nc">Update</span><span class="o">(</span><span class="n">id</span><span class="k">:</span> <span class="kt">Int</span><span class="o">,</span> <span class="n">value</span><span class="k">:</span> <span class="kt">String</span><span class="o">)</span>

<span class="k">val</span> <span class="n">probe</span> <span class="k">=</span> <span class="k">new</span> <span class="nc">TestProbe</span><span class="o">(</span><span class="n">system</span><span class="o">)</span> <span class="o">{</span>
  <span class="k">def</span> <span class="n">expectUpdate</span><span class="o">(</span><span class="n">x</span><span class="k">:</span> <span class="kt">Int</span><span class="o">)</span> <span class="k">=</span> <span class="o">{</span>
    <span class="n">expectMsgPF</span><span class="o">()</span> <span class="o">{</span>
      <span class="k">case</span> <span class="nc">Update</span><span class="o">(</span><span class="n">id</span><span class="o">,</span> <span class="n">_</span><span class="o">)</span> <span class="k">if</span> <span class="n">id</span> <span class="o">==</span> <span class="n">x</span> <span class="k">⇒</span> <span class="kc">true</span>
    <span class="o">}</span>
    <span class="n">sender</span> <span class="o">!</span> <span class="s">&quot;ACK&quot;</span>
  <span class="o">}</span>
<span class="o">}</span>
</pre></div>
</div>
<p>You have complete flexibility here in mixing and matching the <tt class="xref py py-class docutils literal"><span class="pre">TestKit</span></tt>
facilities with your own checks and choosing an intuitive name for it. In real
life your code will probably be a bit more complicated than the example given
above; just use the power!</p>
<div class="section" id="replying-to-messages-received-by-probes">
<h4>Replying to Messages Received by Probes</h4>
<p>The probes keep track of the communications channel for replies, if possible,
so they can also reply:</p>
<div class="highlight-scala"><div class="highlight"><pre><span class="k">val</span> <span class="n">probe</span> <span class="k">=</span> <span class="nc">TestProbe</span><span class="o">()</span>
<span class="k">val</span> <span class="n">future</span> <span class="k">=</span> <span class="n">probe</span><span class="o">.</span><span class="n">ref</span> <span class="o">?</span> <span class="s">&quot;hello&quot;</span>
<span class="n">probe</span><span class="o">.</span><span class="n">expectMsg</span><span class="o">(</span><span class="mi">0</span> <span class="n">millis</span><span class="o">,</span> <span class="s">&quot;hello&quot;</span><span class="o">)</span> <span class="c1">// TestActor runs on CallingThreadDispatcher</span>
<span class="n">probe</span><span class="o">.</span><span class="n">sender</span> <span class="o">!</span> <span class="s">&quot;world&quot;</span>
<span class="n">assert</span><span class="o">(</span><span class="n">future</span><span class="o">.</span><span class="n">isCompleted</span> <span class="o">&amp;&amp;</span> <span class="n">future</span><span class="o">.</span><span class="n">value</span> <span class="o">==</span> <span class="nc">Some</span><span class="o">(</span><span class="nc">Right</span><span class="o">(</span><span class="s">&quot;world&quot;</span><span class="o">)))</span>
</pre></div>
</div>
</div>
<div class="section" id="forwarding-messages-received-by-probes">
<h4>Forwarding Messages Received by Probes</h4>
<p>Given a destination actor <tt class="docutils literal"><span class="pre">dest</span></tt> which in the nominal actor network would
receive a message from actor <tt class="docutils literal"><span class="pre">source</span></tt>. If you arrange for the message to be
sent to a <tt class="xref py py-class docutils literal"><span class="pre">TestProbe</span></tt> <tt class="docutils literal"><span class="pre">probe</span></tt> instead, you can make assertions
concerning volume and timing of the message flow while still keeping the
network functioning:</p>
<div class="highlight-scala"><div class="highlight"><pre><span class="k">class</span> <span class="nc">Source</span><span class="o">(</span><span class="n">target</span><span class="k">:</span> <span class="kt">ActorRef</span><span class="o">)</span> <span class="k">extends</span> <span class="nc">Actor</span> <span class="o">{</span>
  <span class="k">def</span> <span class="n">receive</span> <span class="k">=</span> <span class="o">{</span>
    <span class="k">case</span> <span class="s">&quot;start&quot;</span> <span class="k">⇒</span> <span class="n">target</span> <span class="o">!</span> <span class="s">&quot;work&quot;</span>
  <span class="o">}</span>
<span class="o">}</span>

<span class="k">class</span> <span class="nc">Destination</span> <span class="k">extends</span> <span class="nc">Actor</span> <span class="o">{</span>
  <span class="k">def</span> <span class="n">receive</span> <span class="k">=</span> <span class="o">{</span>
    <span class="k">case</span> <span class="n">x</span> <span class="k">⇒</span> <span class="c1">// Do something..</span>
  <span class="o">}</span>
<span class="o">}</span>

  <span class="k">val</span> <span class="n">probe</span> <span class="k">=</span> <span class="nc">TestProbe</span><span class="o">()</span>
  <span class="k">val</span> <span class="n">source</span> <span class="k">=</span> <span class="n">system</span><span class="o">.</span><span class="n">actorOf</span><span class="o">(</span><span class="nc">Props</span><span class="o">(</span><span class="k">new</span> <span class="nc">Source</span><span class="o">(</span><span class="n">probe</span><span class="o">.</span><span class="n">ref</span><span class="o">)))</span>
  <span class="k">val</span> <span class="n">dest</span> <span class="k">=</span> <span class="n">system</span><span class="o">.</span><span class="n">actorOf</span><span class="o">(</span><span class="nc">Props</span><span class="o">[</span><span class="kt">Destination</span><span class="o">])</span>
  <span class="n">source</span> <span class="o">!</span> <span class="s">&quot;start&quot;</span>
  <span class="n">probe</span><span class="o">.</span><span class="n">expectMsg</span><span class="o">(</span><span class="s">&quot;work&quot;</span><span class="o">)</span>
  <span class="n">probe</span><span class="o">.</span><span class="n">forward</span><span class="o">(</span><span class="n">dest</span><span class="o">)</span>
</pre></div>
</div>
<p>The <tt class="docutils literal"><span class="pre">dest</span></tt> actor will receive the same message invocation as if no test probe
had intervened.</p>
</div>
<div class="section" id="auto-pilot">
<h4>Auto-Pilot</h4>
<p>Receiving messages in a queue for later inspection is nice, but in order to
keep a test running and verify traces later you can also install an
<tt class="xref py py-class docutils literal"><span class="pre">AutoPilot</span></tt> in the participating test probes (actually in any
<tt class="xref py py-class docutils literal"><span class="pre">TestKit</span></tt>) which is invoked before enqueueing to the inspection queue.
This code can be used to forward messages, e.g. in a chain <tt class="docutils literal"><span class="pre">A</span> <span class="pre">--&gt;</span> <span class="pre">Probe</span> <span class="pre">--&gt;</span>
<span class="pre">B</span></tt>, as long as a certain protocol is obeyed.</p>
<div class="highlight-scala"><div class="highlight"><pre><span class="k">val</span> <span class="n">probe</span> <span class="k">=</span> <span class="nc">TestProbe</span><span class="o">()</span>
<span class="n">probe</span><span class="o">.</span><span class="n">setAutoPilot</span><span class="o">(</span><span class="k">new</span> <span class="nc">TestActor</span><span class="o">.</span><span class="nc">AutoPilot</span> <span class="o">{</span>
  <span class="k">def</span> <span class="n">run</span><span class="o">(</span><span class="n">sender</span><span class="k">:</span> <span class="kt">ActorRef</span><span class="o">,</span> <span class="n">msg</span><span class="k">:</span> <span class="kt">Any</span><span class="o">)</span><span class="k">:</span> <span class="kt">Option</span><span class="o">[</span><span class="kt">TestActor.AutoPilot</span><span class="o">]</span> <span class="k">=</span>
    <span class="n">msg</span> <span class="k">match</span> <span class="o">{</span>
      <span class="k">case</span> <span class="s">&quot;stop&quot;</span> <span class="k">⇒</span> <span class="nc">None</span>
      <span class="k">case</span> <span class="n">x</span>      <span class="k">⇒</span> <span class="n">testActor</span><span class="o">.</span><span class="n">tell</span><span class="o">(</span><span class="n">x</span><span class="o">,</span> <span class="n">sender</span><span class="o">);</span> <span class="nc">Some</span><span class="o">(</span><span class="k">this</span><span class="o">)</span>
    <span class="o">}</span>
<span class="o">})</span>
</pre></div>
</div>
<p>The <tt class="xref py py-meth docutils literal"><span class="pre">run</span></tt> method must return the auto-pilot for the next message, wrapped
in an <tt class="xref py py-class docutils literal"><span class="pre">Option</span></tt>; setting it to <tt class="xref py py-obj docutils literal"><span class="pre">None</span></tt> terminates the auto-pilot.</p>
</div>
<div class="section" id="caution-about-timing-assertions">
<h4>Caution about Timing Assertions</h4>
<p>The behavior of <tt class="xref py py-meth docutils literal"><span class="pre">within</span></tt> blocks when using test probes might be perceived
as counter-intuitive: you need to remember that the nicely scoped deadline as
described <a class="reference internal" href="#testkit-within"><em>above</em></a> is local to each probe. Hence, probes
do not react to each other&#8217;s deadlines or to the deadline set in an enclosing
<tt class="xref py py-class docutils literal"><span class="pre">TestKit</span></tt> instance:</p>
<div class="highlight-scala"><div class="highlight"><pre><span class="k">class</span> <span class="nc">SomeTest</span> <span class="k">extends</span> <span class="nc">TestKit</span><span class="o">(</span><span class="nc">_system</span><span class="k">:</span> <span class="kt">ActorSystem</span><span class="o">)</span> <span class="k">with</span> <span class="nc">ImplicitSender</span> <span class="o">{</span>

  <span class="k">val</span> <span class="n">probe</span> <span class="k">=</span> <span class="nc">TestProbe</span><span class="o">()</span>

  <span class="n">within</span><span class="o">(</span><span class="mi">100</span> <span class="n">millis</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">probe</span><span class="o">.</span><span class="n">expectMsg</span><span class="o">(</span><span class="s">&quot;hallo&quot;</span><span class="o">)</span>  <span class="c1">// Will hang forever!</span>
  <span class="o">}</span>
<span class="o">}</span>
</pre></div>
</div>
<p>This test will hang indefinitely, because the <tt class="xref py py-meth docutils literal"><span class="pre">expectMsg</span></tt> call does not
see any deadline. Currently, the only option is to use <tt class="docutils literal"><span class="pre">probe.within</span></tt> in the
above code to make it work; later versions may include lexically scoped
deadlines using implicit arguments.</p>
</div>
</div>
</div>
<div class="section" id="callingthreaddispatcher">
<span id="testcallingthreaddispatcherref"></span><h2>CallingThreadDispatcher</h2>
<p>The <tt class="xref py py-class docutils literal"><span class="pre">CallingThreadDispatcher</span></tt> serves good purposes in unit testing, as
described above, but originally it was conceived in order to allow contiguous
stack traces to be generated in case of an error. As this special dispatcher
runs everything which would normally be queued directly on the current thread,
the full history of a message&#8217;s processing chain is recorded on the call stack,
so long as all intervening actors run on this dispatcher.</p>
<div class="section" id="how-to-use-it">
<h3>How to use it</h3>
<p>Just set the dispatcher as you normally would:</p>
<div class="highlight-scala"><div class="highlight"><pre><span class="k">import</span> <span class="nn">akka.testkit.CallingThreadDispatcher</span>
<span class="k">val</span> <span class="n">ref</span> <span class="k">=</span> <span class="n">system</span><span class="o">.</span><span class="n">actorOf</span><span class="o">(</span><span class="nc">Props</span><span class="o">[</span><span class="kt">MyActor</span><span class="o">].</span><span class="n">withDispatcher</span><span class="o">(</span><span class="nc">CallingThreadDispatcher</span><span class="o">.</span><span class="nc">Id</span><span class="o">))</span>
</pre></div>
</div>
</div>
<div class="section" id="how-it-works">
<h3>How it works</h3>
<p>When receiving an invocation, the <tt class="xref py py-class docutils literal"><span class="pre">CallingThreadDispatcher</span></tt> checks
whether the receiving actor is already active on the current thread. The
simplest example for this situation is an actor which sends a message to
itself. In this case, processing cannot continue immediately as that would
violate the actor model, so the invocation is queued and will be processed when
the active invocation on that actor finishes its processing; thus, it will be
processed on the calling thread, but simply after the actor finishes its
previous work. In the other case, the invocation is simply processed
immediately on the current thread. Futures scheduled via this dispatcher are
also executed immediately.</p>
<p>This scheme makes the <tt class="xref py py-class docutils literal"><span class="pre">CallingThreadDispatcher</span></tt> work like a general
purpose dispatcher for any actors which never block on external events.</p>
<p>In the presence of multiple threads it may happen that two invocations of an
actor running on this dispatcher happen on two different threads at the same
time. In this case, both will be processed directly on their respective
threads, where both compete for the actor&#8217;s lock and the loser has to wait.
Thus, the actor model is left intact, but the price is loss of concurrency due
to limited scheduling. In a sense this is equivalent to traditional mutex style
concurrency.</p>
<p>The other remaining difficulty is correct handling of suspend and resume: when
an actor is suspended, subsequent invocations will be queued in thread-local
queues (the same ones used for queuing in the normal case). The call to
<tt class="xref py py-meth docutils literal"><span class="pre">resume</span></tt>, however, is done by one specific thread, and all other threads
in the system will probably not be executing this specific actor, which leads
to the problem that the thread-local queues cannot be emptied by their native
threads. Hence, the thread calling <tt class="xref py py-meth docutils literal"><span class="pre">resume</span></tt> will collect all currently
queued invocations from all threads into its own queue and process them.</p>
</div>
<div class="section" id="limitations">
<h3>Limitations</h3>
<p>If an actor&#8217;s behavior blocks on a something which would normally be affected
by the calling actor after having sent the message, this will obviously
dead-lock when using this dispatcher. This is a common scenario in actor tests
based on <tt class="xref py py-class docutils literal"><span class="pre">CountDownLatch</span></tt> for synchronization:</p>
<div class="highlight-scala"><div class="highlight"><pre><span class="k">val</span> <span class="n">latch</span> <span class="k">=</span> <span class="k">new</span> <span class="nc">CountDownLatch</span><span class="o">(</span><span class="mi">1</span><span class="o">)</span>
<span class="n">actor</span> <span class="o">!</span> <span class="n">startWorkAfter</span><span class="o">(</span><span class="n">latch</span><span class="o">)</span>   <span class="c1">// actor will call latch.await() before proceeding</span>
<span class="n">doSomeSetupStuff</span><span class="o">()</span>
<span class="n">latch</span><span class="o">.</span><span class="n">countDown</span><span class="o">()</span>
</pre></div>
</div>
<p>The example would hang indefinitely within the message processing initiated on
the second line and never reach the fourth line, which would unblock it on a
normal dispatcher.</p>
<p>Thus, keep in mind that the <tt class="xref py py-class docutils literal"><span class="pre">CallingThreadDispatcher</span></tt> is not a
general-purpose replacement for the normal dispatchers. On the other hand it
may be quite useful to run your actor network on it for testing, because if it
runs without dead-locking chances are very high that it will not dead-lock in
production.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">The above sentence is unfortunately not a strong guarantee, because your
code might directly or indirectly change its behavior when running on a
different dispatcher. If you are looking for a tool to help you debug
dead-locks, the <tt class="xref py py-class docutils literal"><span class="pre">CallingThreadDispatcher</span></tt> may help with certain error
scenarios, but keep in mind that it has may give false negatives as well as
false positives.</p>
</div>
</div>
<div class="section" id="benefits">
<h3>Benefits</h3>
<p>To summarize, these are the features with the <tt class="xref py py-class docutils literal"><span class="pre">CallingThreadDispatcher</span></tt>
has to offer:</p>
<blockquote>
<div><ul class="simple">
<li>Deterministic execution of single-threaded tests while retaining nearly full
actor semantics</li>
<li>Full message processing history leading up to the point of failure in
exception stack traces</li>
<li>Exclusion of certain classes of dead-lock scenarios</li>
</ul>
</div></blockquote>
</div>
</div>
<div class="section" id="tracing-actor-invocations">
<span id="actor-logging"></span><h2>Tracing Actor Invocations</h2>
<p>The testing facilities described up to this point were aiming at formulating
assertions about a system’s behavior. If a test fails, it is usually your job
to find the cause, fix it and verify the test again. This process is supported
by debuggers as well as logging, where the Akka toolkit offers the following
options:</p>
<ul>
<li><p class="first"><em>Logging of exceptions thrown within Actor instances</em></p>
<p>This is always on; in contrast to the other logging mechanisms, this logs at
<tt class="docutils literal"><span class="pre">ERROR</span></tt> level.</p>
</li>
<li><p class="first"><em>Logging of message invocations on certain actors</em></p>
<p>This is enabled by a setting in the <a class="reference internal" href="../general/configuration.html#configuration"><em>Configuration</em></a> — namely
<tt class="docutils literal"><span class="pre">akka.actor.debug.receive</span></tt> — which enables the <tt class="xref py py-meth docutils literal"><span class="pre">loggable</span></tt>
statement to be applied to an actor’s <tt class="xref py py-meth docutils literal"><span class="pre">receive</span></tt> function:</p>
</li>
</ul>
<div class="highlight-scala"><div class="highlight"><pre><span class="k">import</span> <span class="nn">akka.event.LoggingReceive</span>
<span class="k">def</span> <span class="n">receive</span> <span class="k">=</span> <span class="nc">LoggingReceive</span> <span class="o">{</span>
  <span class="k">case</span> <span class="n">msg</span> <span class="k">⇒</span> <span class="c1">// Do something...</span>
<span class="o">}</span>
</pre></div>
</div>
<dl class="docutils">
<dt>.</dt>
<dd><p class="first">If the abovementioned setting is not given in the <a class="reference internal" href="../general/configuration.html#configuration"><em>Configuration</em></a>, this method will
pass through the given <tt class="xref py py-class docutils literal"><span class="pre">Receive</span></tt> function unmodified, meaning that
there is no runtime cost unless actually enabled.</p>
<p class="last">The logging feature is coupled to this specific local mark-up because
enabling it uniformly on all actors is not usually what you need, and it
would lead to endless loops if it were applied to <tt class="xref py py-class docutils literal"><span class="pre">EventHandler</span></tt>
listeners.</p>
</dd>
</dl>
<ul>
<li><p class="first"><em>Logging of special messages</em></p>
<p>Actors handle certain special messages automatically, e.g. <tt class="xref py py-obj docutils literal"><span class="pre">Kill</span></tt>,
<tt class="xref py py-obj docutils literal"><span class="pre">PoisonPill</span></tt>, etc. Tracing of these message invocations is enabled by
the setting <tt class="docutils literal"><span class="pre">akka.actor.debug.autoreceive</span></tt>, which enables this on all
actors.</p>
</li>
<li><p class="first"><em>Logging of the actor lifecycle</em></p>
<p>Actor creation, start, restart, monitor start, monitor stop and stop may be traced by
enabling the setting <tt class="docutils literal"><span class="pre">akka.actor.debug.lifecycle</span></tt>; this, too, is enabled
uniformly on all actors.</p>
</li>
</ul>
<p>All these messages are logged at <tt class="docutils literal"><span class="pre">DEBUG</span></tt> level. To summarize, you can enable
full logging of actor activities using this configuration fragment:</p>
<div class="highlight-scala"><div class="highlight"><pre><span class="n">akka</span> <span class="o">{</span>
  <span class="n">loglevel</span> <span class="k">=</span> <span class="nc">DEBUG</span>
  <span class="n">actor</span> <span class="o">{</span>
    <span class="n">debug</span> <span class="o">{</span>
      <span class="n">receive</span> <span class="k">=</span> <span class="n">on</span>
      <span class="n">autoreceive</span> <span class="k">=</span> <span class="n">on</span>
      <span class="n">lifecycle</span> <span class="k">=</span> <span class="n">on</span>
    <span class="o">}</span>
  <span class="o">}</span>
<span class="o">}</span>
</pre></div>
</div>
</div>
</div>


          </div>
          <div class="span3"><p class="contents-title">Contents</p>
              <div id="scroller-anchor">
                <div id="scroller">
                  <div id="toc"></div>
                </div>
              </div></div>
        </div>
      </div>
    </div>
  </div>
  <div class="footer">
  <div class="container">
    <ul>
      <li><h5>Akka</h5></li>
      <li><a href="http://akka.io/docs">Documentation</a></li>
      <li><a href="http://akka.io/downloads">Downloads</a></li>
    </ul>
    <ul>
      <li><h5>Contribute</h5></li>
      <li><a href="http://github.com/akka/akka">Source Code</a></li>
      <li><a href="http://groups.google.com/group/akka-user">Mailing List</a></li>      
      <li><a href="http://www.assembla.com/spaces/akka/tickets">Report a Bug</a></li>      
    </ul>
    <ul>
      <li><h5>Company</h5></li>
      <li><a href="http://typesafe.com/products/typesafe-subscription">Commercial Support</a></li>
      <li><a href="http://akka.io/team">Team</a></li>
      <li><a href="mailto:info@typesafe.com">Contact</a></li>
    </ul>
    <ul>
      <li><img src="../_static/watermark.png" align="center"/></li>
    </ul>
  </div>
  <div class="container copyright">
    <p style="float: left;">
      © 2012 <a href="http://typesafe.com/">Typesafe Inc.</a> <span class="license">Akka is Open Source and available under the Apache 2 License.</span>
    </p>
    <p style="float: right; font-size: 12px;">
      Last updated: Apr 13, 2012
    </p>          
  </div>
</div>
<script type="text/javascript">
  $('#toc').toc();
</script>
  

  </body>
</html>